<?php

class UsersController extends Zend_Controller_Action
{
    public function init()
    {
        $this->table = new Default_Model_DbTable_Users();
        $info = $this->table->info();
        $this->primary = $info['primary'][1];
        $this->cols = $info['cols'];

        $this->form = new Default_Form_User();

        $this->locale = Zend_Registry::get('Zend_Locale');

        $this->controller = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();

        $this->url = 'http://'.$_SERVER['SERVER_NAME'];//.$this->getFrontController()->getBaseUrl();

        $this->urlParams = null;
        if (strlen($this->_getParam('by'))) {
            $this->urlParams .= '/by/'.$this->_getParam('by');
        }
        if (strlen($this->_getParam('sort'))) {
            $this->urlParams .= '/sort/'.$this->_getParam('sort');
        }
        if (strlen($this->_getParam('page'))) {
            $this->urlParams .= '/page/'.$this->_getParam('page');
        }
    }

    function indexAction()
    {
        $this->view->message = $this->_getParam('message');

        $query = $this->table->select()
                ->setIntegrityCheck(false)
                ->from(
                    array('u' => $this->table->_name),
                    array('*',
                        'group_name' => 'g.name')
                    )
                ->joinLeft(
                    array('g' => 'groups'),
                    'u.group_id = g.id',
                    array()
                )
                ->order(
                    $this->_getParam('by', $this->primary).' '.$this->_getParam('sort', 'ASC')
                );
        //echo $query->__toString();
        $result = $this->table->fetchAll($query);

        $paginator = Zend_Paginator::factory($result->toArray());
        $paginator->setItemCountPerPage(10);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));

        $this->view->fields = array(
                $this->primary  => 'ID',
                'email'      => 'epasts',
                'name'          => 'Vārds',
                'surname'       => 'uzvārds',
                //'date_created'  => 'Izveidošanas datums',
                'group_name'      => 'Grupa',
            );

        $editUrl = $this->view->url(
            array(
                'controller' => $this->controller,
                'action' => 'edit',
                $this->primary => '{ID}'
            )
        );

        $deleteUrl = $this->view->url(
            array(
                'controller' => $this->controller,
                'action' => 'delete',
                $this->primary => '{ID}'
            )
        );

        $this->view->options = array(
            'label' => 'Opcijas',
            'primary' => $this->primary,
            'options' => array(
                'Labot' => $editUrl,
                'Dzēst' => $deleteUrl
            )
        );

        $this->view->paginator = $paginator;
    }

    public function editAction()
    {
        $editId = $this->_getParam($this->primary);

        // load row data and save to form
        if (!empty($editId)) {
            $result = $this->table->find($editId);
            $data = $result->toArray();
            $this->form->populate($data[0]);
            unset($data);
        }

        // validate form and save new data
        if ($this->_request->isPost()) {
            $values = $this->_request->getPost();

            // prepare values
            foreach ($this->cols AS $column) {
                $data[$column] = $values[$column];
            }

            if ($this->form->isValid($values) AND !empty($editId)) {
                $where = $this->table->getAdapter()->quoteInto($this->primary.' = ?', $editId);
                $this->table->update($data, $where);

                $this->_redirect(
                    $this->url.$this->_helper->url('index').$this->urlParams
                );

            } else {
                $this->form->populate($values);
            }
        }
        $this->view->form = $this->form;
    }

    public function addAction()
    {

        // validate form and save new data
        if ($this->_request->isPost()) {
            $values = $this->_request->getPost();

            // prepare values
            foreach ($this->cols AS $column) {
                $data[$column] = $values[$column];
            }

            if ($this->form->isValid($values)) {
                $this->table->insert($data);
                $this->_forward('index', null, null, array('message' => 'Veiksmīgi pievienots'));
            } else {
                $this->form->populate($values);
            }
        }

        $this->view->form = $this->form;
    }

    public function deleteAction()
    {
        $editId = $this->_getParam($this->primary);

        $where = $this->table->getAdapter()->quoteInto($this->primary.' = ?', $editId);
        $result = $this->table->delete($where);
        $this->_forward('index', null, null, array('message' => 'Veiksmīgi izdzēsts'));
    }


}